package com.other.src.main.java.com.kuang.single;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

public class LazyMan {

    private static boolean qinjiang = false;

    private volatile static LazyMan lazyMan;

    private LazyMan () {
        synchronized (LazyMan.class) {
            if (qinjiang == false){
                qinjiang = true;
            }else {
                throw new RuntimeException("不要试图用反射破换单例");
            }

        }
    }

    //DCL懒汉
    public static LazyMan getLazyMan() {
        if (lazyMan == null){
            synchronized (LazyMan.class){
                if (lazyMan == null){
                    lazyMan = new LazyMan();// 不是一个原子性操作

/*
* 1.分配内存空间
* 2.执行构造方法，初始化对象
* 3.把这个对象指向这个空间
* */
               }
            }
        }

        return lazyMan; // 此时该对象还没完成初始化，
    }

    public static void main(String[] args) throws Exception {
//        LazyMan man = LazyMan.getLazyMan();

        Field qinjiang = LazyMan.class.getDeclaredField("qinjiang");
        qinjiang.setAccessible(true);

        Constructor<LazyMan> declaredConstructor = LazyMan.class.getDeclaredConstructor(null);
        declaredConstructor.setAccessible(true);
        LazyMan man = declaredConstructor.newInstance();

        qinjiang.set(man,false);

        LazyMan lazyMan = declaredConstructor.newInstance();
        System.out.println(man);
        System.out.println(lazyMan);
    }
}
